package com.jd.samples;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * Servlet implementation class TestServlet
 */
public class TestServlet extends HttpServlet {
	final Logger logger = LoggerFactory.getLogger(TestServlet.class);
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
	 * 验证url和token
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戮
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr"); 
        
        PrintWriter out = response.getWriter();
        // 通过检验 signature 对请求进行校验，若校验成功则原样返回 echostr，表示接入成功，否则接入失败
       if(SignUtil.checkSignature(signature, timestamp, nonce)){
           out.print(echostr);
       }

       out.close();
       out = null; 
	}

	/**
	 *用户向公众平台发信息并自动返回信息
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		   message(request,response);  
		   
		
	}

	public void init() throws ServletException {
	}

	 /** 
     *@author haibing.xiao 
     *@return   
     *@exception ServletException, IOException 
     *@param 
     *  
     * <p>XML组装组件</p> 
     */  
     private void message(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{  
           
            InputStream is = request.getInputStream();  
            // 取HTTP请求流长度  
            int size = request.getContentLength();  
            // 用于缓存每次读取的数据  
            byte[] buffer = new byte[size];  
            // 用于存放结果的数组  
            byte[] xmldataByte = new byte[size];  
            int count = 0;  
            int rbyte = 0;  
            // 循环读取  
            while (count < size) {   
                // 每次实际读取长度存于rbyte中  
                rbyte = is.read(buffer);   
                for(int i=0;i<rbyte;i++) {  
                    xmldataByte[count + i] = buffer[i];  
                }  
                count += rbyte;  
            }  
            is.close();  
            String requestStr = new String(xmldataByte, "UTF-8");  
              
              
            try{  
                manageMessage(requestStr,request,response);  
            }catch(Exception e){  
                e.printStackTrace();  
            }  
              
        }  
   
       
    /** 
     * @author haibing.xiao 
     * @return  
     * @exception ServletException, IOException 
     * @param 
     *  
     * <p>业务转发组件</p> 
     *  
     */  
      private void  manageMessage(String requestStr,HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{  
              
            String responseStr;  
             
            try {  
                 XMLSerializer xmlSerializer=new XMLSerializer();  
                 JSONObject jsonObject =(JSONObject) xmlSerializer.read(requestStr);  
                 String event =jsonObject.getString("Event");  
                 String msgtype =jsonObject.getString("MsgType");  
                 if("CLICK".equals(event) && "event".equals(msgtype)){ //菜单click事件  
                     String eventkey =jsonObject.getString("EventKey");  
                     if("hytd_001".equals(eventkey)){ // hytd_001 这是好友团队按钮的标志值  
                         jsonObject.put("Content", "欢迎使用好友团队菜单click按钮.");  
                     }  
                      
                 }  
                 responseStr =creatRevertText(jsonObject);//创建XML  
                 logger.info("responseStr:"+responseStr);  
                 OutputStream os =response.getOutputStream();  
                 os.write(responseStr.getBytes("UTF-8"));  
            }   catch (Exception e) {  
                e.printStackTrace();  
            }  
              
    }  
    private String creatRevertText(JSONObject jsonObject){  
            StringBuffer revert =new StringBuffer();  
            revert.append("<xml>");  
            revert.append("<ToUserName><![CDATA["+jsonObject.get("ToUserName")+"]]></ToUserName>");  
            revert.append("<FromUserName><![CDATA["+jsonObject.get("FromUserName")+"]]></FromUserName>");  
            revert.append("<CreateTime>"+jsonObject.get("CreateTime")+"</CreateTime>");  
            revert.append("<MsgType><![CDATA[text]]></MsgType>");  
            revert.append("<Content><![CDATA["+jsonObject.get("Content")+"]]></Content>");  
            revert.append("<FuncFlag>0</FuncFlag>");  
            revert.append("</xml>");  
            return revert.toString();  
        }  

}
